<template>
  <el-dialog title="修改密码" v-model:model-value="isShowDialog" append-to-body	>
    <el-form :model="form" :rules="formRules" ref="formRef" :label-width="100">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input type="password" v-model="form.oldPassword" placeholder="输入旧密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="form.newPassword" placeholder="输入新密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="再次输入" prop="newPassword_2">
        <el-input type="password" v-model="form.newPassword_2" placeholder="再次输入新密码" show-password></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="isShowDialog = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { logout, updatePassword } from "@/api/login";
import { useDelCache } from "@/compositions/main/useDelCache";
const store = useStore()
const router = useRouter()

const props = defineProps<{
  show: boolean,
}>()
const emits = defineEmits([
  'update:show'
])
const isShowDialog = computed({
  get() {
    return props.show
  },
  set(newValue) {
    emits('update:show', newValue)
  }
})

const formRules = ref({
  oldPassword: [{
    required: true,
    message: '请输入旧密码',
    trigger: 'blur'
  }],
  newPassword: [{
    required: true,
    message: '请输入新密码',
    trigger: 'blur'
  }, {
    trigger: 'blur',
    validator: (rule: any, value: string, callback: any) => {
      if (!/^[a-zA-Z0-9]{6,20}$/.test(value)) {
        callback('密码为4至16位字母或数字')
        return
      }

      callback()
    }
  }],
  newPassword_2: [{
    trigger: 'blur',
    message: '请再次输入新密码',
    required: true,
  }, {
    trigger: 'blur',
    validator(rule: any, value: any, callback: any) {
      if (form.newPassword !== form.newPassword_2) {
        callback('两次密码输入不一致')
        return
      }

      callback()
    },
  }]
})
const form = reactive<{
  oldPassword: string,
  newPassword: string,
  newPassword_2?: string,
}>({
  oldPassword: '',
  newPassword: '',
  newPassword_2: '',
})
const formRef = ref()

const submit = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      delete form.newPassword_2
      const rs = await updatePassword(form)

      if (rs.code === 200) {
        ElMessage.success('修改成功')
        isShowDialog.value = false
        useDelCache()

        const rs = await logout();
        if (rs.code == 200) {
          ElMessage.info("请重新登录");
          const path = sessionStorage.getItem('loginPath') || '/login'
          router.replace(path)
        }
      } else {
        formRef.value?.resetFields()
      }
    }
  })
}
</script>

<style scoped lang="scss"></style>
